package com.onefish.toolkit.netty.websocket;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.text.SimpleDateFormat;
import java.util.Date;


//泛型TextWebSocketFrame：WebSocket处理的处理文本类型
public class MyNettyServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //接收WebSocket客户端发送来的数据（Websocket以frame的形式传递数据）
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        System.out.println(sdf.format(new Date()) + "【服务端】接受的请求来自：" + ctx.channel().remoteAddress() + " ,消息内容：" + frame.text());
        //向WebSocket客户端发送数据
        ctx.channel().writeAndFlush(new TextWebSocketFrame(sdf.format(new Date()) + " 请向【客户端发】送消息：hello client..."));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date()) + " 【客户端】 " + ctx.channel().remoteAddress() + "加入连接");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date()) + "【客户端】 " + ctx.channel().remoteAddress() + "断开连接");
    }
}

